#include "bsp_spi.h"



void spi_init(SPI_TypeDef *spi)
{
    
	GPIO_InitTypeDef GPIO_InitStructure;
    
	if (spi == SPI1) {
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    } else if (spi == SPI2) {
        /* you can add SPI2 code here */
    }
	
    if (spi == SPI1) {
        /* SCK:PA5  MISO:PA6  MOSI:PA7 */
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
        GPIO_Init(GPIOA, &GPIO_InitStructure);
        /* CS: PA4 */
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
        GPIO_Init(GPIOA, &GPIO_InitStructure);
        GPIO_SetBits(GPIOA, GPIO_Pin_4);
    } else if (spi == SPI2) {
        /* you can add SPI2 code here */
    }
	
	
	SPI_InitTypeDef SPI_InitStructure;

    SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //SPI 设置为双线双向全双工
    SPI_InitStructure.SPI_Mode = SPI_Mode_Master;                      //设置为主 SPI
    SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;                  //SPI 发送接收 8 位帧结构
    SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;                         //时钟悬空低
    SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;                       //数据捕获于第一个时钟沿
    //TODO 以后可以尝试硬件 CS
    SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;                          //内部  NSS 信号由 SSI 位控制
    SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2; //波特率预分频值为 2
    SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;                 //数据传输从 MSB 位开始
    SPI_InitStructure.SPI_CRCPolynomial = 7;                           // CRC 值计算的多项式

	if (spi == SPI1) {
    SPI_I2S_DeInit(SPI1);
    SPI_Init(SPI1, &SPI_InitStructure);
    SPI_CalculateCRC(SPI1, DISABLE);
    SPI_Cmd(SPI1, ENABLE);
	}else if (spi == SPI2) {
        /* you can add SPI2 code here */
    }
}



